package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kuiandjie.entity.Employee;
import com.kuiandjie.service.EmployeeService;

public class AppServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//判断请求
		//method为空则跳转的登录页
		String method = request.getParameter("m");
		if("login".equals(method)) {
			//获取请求方式，post则验证信息，get发送错误
			String type = request.getMethod();
			
			if("POST".equals(type)) {
				login(request, response);
			} else {
				response.sendError(404, "页面未找到");
			}
		} else {
			request.getRequestDispatcher("WEB-INF/views/login.jsp").forward(request, response);
		}
	}

	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//使用ajax时必须设置contextType
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//获取用户名和密码
		String name = request.getParameter("name");
		String password = request.getParameter("passwrod");
		
		if(name != null && password != null) {
			//EmployeeService中的checkLogin()方法
			EmployeeService es = new EmployeeService();
			Employee employee = es.checkLogin(name, password);
			if(employee != null) {
				//session中保存登录者的id和name
				HttpSession session = request.getSession();
				employee.setPassword("");
				session.setAttribute("employee", employee);
				
				out.println("main.jspx");
			} else {
				out.println("10002");
			}
		} else {
			out.println("10001");
		}
		
		out.flush();
		out.close();
	}
	
}
